package cn.ssdcc.dkserver.controller;

import cn.ssdcc.dkserver.entity.*;
import cn.ssdcc.dkserver.exception.BusinessException;
import cn.ssdcc.dkserver.util.IsNullUtil;
import com.alibaba.fastjson.JSON;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.UUID;

@Controller
@RequestMapping("/MusicApi")
@Slf4j
public class MusicController extends CommonController {

    private static List<Music> musicList = new ArrayList<Music>();
    private static Long nexttime = 0L;


    @RequestMapping(value = "/GetMusicList", method = RequestMethod.POST)
    @ResponseBody
    public DkResponse<List<Music>> getMusicList() {
        return new DkResponse<List<Music>>(musicList);
    }

    @RequestMapping(value = "/UpMusicByUrl", method = RequestMethod.POST)
    @ResponseBody
    public DkResponse<Music> UpMusicByUrl(@RequestBody Music music) {
        musicToolBiz.UpMusicByUrlChack(music);
        DkResponse<Music> dkResponse = new DkResponse<>();
        List<Music> musics = musicMapper.selectMusicByThirdid(music.getThirdid());
        if (musics.size() != 0){
            if (musics.size() > 1){
                log.warn("歌曲:["+musics.get(0).getName()+"]出现异常,三方ID:["+musics.get(0).getThirdid()+"]请检查文件是否重复");
            }
            dkResponse.setData(musics.get(0));
            return dkResponse;
        }
        music = musicToolBiz.downloadMusicByUrl(music);
        musics = musicMapper.selectMusicByThirdid(music.getThirdid());
        if (musics.size() != 0){
            if (musics.size() > 1){
                log.warn("歌曲:["+musics.get(0).getName()+"]出现异常,三方ID:["+musics.get(0).getThirdid()+"]请检查文件是否重复");
            }
            dkResponse.setData(musics.get(0));
            return dkResponse;
        }else {
            throw new BusinessException("录入失败");
        }
    }

    @RequestMapping(value = "/SelectMusic", method = RequestMethod.POST)
    @ResponseBody
    public DkResponse<List<Music>> SelectMusic(@RequestBody Music music) {
        List<Music> musics = musicMapper.selectMusic("%"+music.getName()+"%",music.getName());
        DkResponse<List<Music>> dkResponse = new DkResponse<>();
        dkResponse.setData(musics);
        return dkResponse;
    }

    @RequestMapping(value = "/SetMusic", method = RequestMethod.POST)
    @ResponseBody
    public DkResponse SetMusic(@RequestBody Music music) {
        musicToolBiz.SetMusicChack(music);
        if (musicList.size() == 0){
            music.setStarttime(System.currentTimeMillis());
        }
        musicList.add(music);
        webSocket.sendAllMessage("MusicList");
        return new DkResponse();
    }

    @RequestMapping(value = "/NextMusic", method = RequestMethod.POST)
    @ResponseBody
    public DkResponse NextMusic(@RequestBody Music music) {
        if ((System.currentTimeMillis()-nexttime) > 3000){
            if (musicList.size() > 0){
                nexttime = System.currentTimeMillis();
                musicList.remove(0);
            }
            if (musicList.size() > 0){
                musicList.get(0).setStarttime(System.currentTimeMillis());
            }else {
                List<String > musicIdList = musicMapper.selectMusicAndGroupGroupid("1");
                if (musicIdList.size()>0){
                    Random r = new Random();
                    int ran1 = r.nextInt(musicIdList.size());
                    List<Music> musics = musicMapper.selectMusicById(musicIdList.get(ran1));
                    if (musics.size() !=0){
                        musicList.add(musics.get(0));
                        musicList.get(0).setStarttime(System.currentTimeMillis());
                    }else {
                        log.warn("歌曲ID："+musicIdList.get(ran1)+"没找到");
                    }
                }
            }
            webSocket.sendAllMessage("MusicList");
        }
        return new DkResponse();
    }

    //创建新的歌单
    @RequestMapping(value = "/CreateMusicGroup", method = RequestMethod.POST)
    @ResponseBody
    public DkResponse<MusicGroup> CreateMusicGroup(@RequestBody MusicGroup musicGroup) {
        if (IsNullUtil.IsNullString(musicGroup.getName())){
            throw new BusinessException("歌单名称为空");
        }
        if (IsNullUtil.IsNullString(musicGroup.getAbout())){
            musicGroup.setAbout("啥都没写！");
        }
        if (IsNullUtil.IsNullString(musicGroup.getImg())){
            musicGroup.setImg("https://i.postimg.cc/NFg5BxYm/1024x1024bb.png");
        }
        String uuid = UUID.randomUUID().toString();
        musicGroup.setUuid(uuid);
        User user = userBiz.getUserMsgByDeviceid(musicGroup.getUserid());
        musicGroup.setUserid(user.getId());
        musicMapper.inserteMusicGroup(musicGroup);
        List<MusicGroup> musicGroups = musicMapper.selectMusicGroupByUuid(uuid);
        if (musicGroups.size() == 0){
            throw new BusinessException("创建失败");
        }
        if (musicGroups.size() > 1){
            log.warn("歌单:["+musicGroups.get(0).getName()+"]出现异常,UUID:["+uuid+"]请检查是否重复");
        }
        DkResponse<MusicGroup> dkResponse = new DkResponse<>();
        dkResponse.setData(musicGroups.get(0));
        return dkResponse;
    }

    //修改歌单歌曲
    @RequestMapping(value = "/updateMusicGroupMusic", method = RequestMethod.POST)
    @ResponseBody
    public DkResponse updateMusicGroupMusic(@RequestBody MusicGroup musicGroup) {
        if (IsNullUtil.IsNullList(musicGroup.getMusicList())){
            musicGroup.setMusicList(new ArrayList<Music>());
        }
        if (IsNullUtil.IsNullString(musicGroup.getId())){
            throw new BusinessException("歌单ID为空");
        }
        if (IsNullUtil.IsNullString(musicGroup.getName())){
            throw new BusinessException("歌单名称为空");
        }
        if (IsNullUtil.IsNullString(musicGroup.getAbout())){
            musicGroup.setAbout("啥都没写！");
        }
        if (IsNullUtil.IsNullString(musicGroup.getImg())){
            musicGroup.setImg("https://i.postimg.cc/NFg5BxYm/1024x1024bb.png");
        }
        musicMapper.updateMusicGroup(musicGroup);
        musicMapper.deleteMusicAndGroupByGroupId(musicGroup.getId());
        List<Music> musicList = musicGroup.getMusicList();
        for (Music music : musicList){
            if (IsNullUtil.IsNotNullString(music.getId())){
                musicMapper.insertMusicAndGroup(musicGroup.getId(),music.getId());
            }
        }
        return new DkResponse();
    }

    //获取歌单信息
    @RequestMapping(value = "/GetMusicGroup", method = RequestMethod.POST)
    @ResponseBody
    public DkResponse<MusicGroup> GetMusicGroup(@RequestBody MusicGroup musicGroup) {
        if (IsNullUtil.IsNullString(musicGroup.getId())){
            throw new BusinessException("歌单ID为空");
        }
        List<MusicGroup> musicGroups = musicMapper.selectMusicGroupById(musicGroup.getId());
        if (musicGroups.size() == 0){
            throw new BusinessException("获取失败");
        }
        musicGroup = musicGroups.get(0);
        List<String > musicIdList = musicMapper.selectMusicAndGroupGroupid(musicGroup.getId());
        List<Music> musicList = new ArrayList<>();
        for (String musicId : musicIdList){
            List<Music> musics = musicMapper.selectMusicById(musicId);
            if (musics.size() !=0){
                musicList.add(musics.get(0));
            }else {
                log.warn("歌曲ID："+musicId+"没找到");
            }
        }
        musicGroup.setMusicList(musicList);
        DkResponse<MusicGroup> dkResponse = new DkResponse<>();
        dkResponse.setData(musicGroup);
        return dkResponse;
    }

    //获取歌单信息
    @RequestMapping(value = "/GetMusicGroupList", method = RequestMethod.POST)
    @ResponseBody
    public DkResponse<List<MusicGroup>> GetMusicGroupList(@RequestBody MusicGroup musicGroup) {
        List<MusicGroup> musicGroups = musicMapper.selectMusicGroupList();
        if (musicGroups.size() == 0){
            throw new BusinessException("获取失败");
        }
        DkResponse<List<MusicGroup>> dkResponse = new DkResponse<>();
        dkResponse.setData(musicGroups);
        return dkResponse;
    }

    //删除歌单
    @RequestMapping(value = "/DeleteMusicGroup", method = RequestMethod.POST)
    @ResponseBody
    public DkResponse DeleteMusicGroup(@RequestBody MusicGroup musicGroup) {
        if (IsNullUtil.IsNullString(musicGroup.getId())){
            throw new BusinessException("歌单ID为空");
        }
        if ("1".equals(musicGroup.getId())){
            throw new BusinessException("首个歌单不能删除");
        }
        musicMapper.deleteMusicAndGroupByGroupId(musicGroup.getId());
        musicMapper.deleteMusicGroupByGroupId(musicGroup.getId());
        return new DkResponse();
    }
    /**
     * 使用对应的参数实体类接收，Music
     * @param file
     * @param req
     */
    @RequestMapping("/UpMusic")
    @ResponseBody
    public DkResponse UpMusic(@RequestParam("file") MultipartFile file,  HttpServletRequest req){
        log.info("文件名："+file.getOriginalFilename());
        Music music = new Music();
        music.setName(req.getParameter("name"));
        music.setArname(req.getParameter("arname"));
        music.setAlname(req.getParameter("alname"));
        music.setImg(req.getParameter("img"));
        String[] types = file.getOriginalFilename().split("\\.");
        music.setType(types[types.length-1]);
        String uuid = UUID.randomUUID().toString();
        music.setThirdid(uuid);
        music.setUuid(uuid);
        music.setUserid(req.getParameter("userid"));
        log.info("歌名："+music.getName());
        String path = musicToolBiz.buildMusicPath("/music/",file.getOriginalFilename(),music);
        log.info(path);
        upLoadBiz.saveMultipartFile(file, DkPath.DataPath+path);
        music.setFile(path);
        User user = userBiz.getUserMsgByDeviceid(music.getUserid());
        music.setUserid(user.getId());
        musicMapper.insertMusic(music);
        return new DkResponse();
    }

    @RequestMapping("/UpMusicImg")
    @ResponseBody
    public DkResponse<String> UpMusicImg(@RequestParam("file") MultipartFile file,  HttpServletRequest req){
        log.info("文件名："+file.getOriginalFilename());
        Music music = new Music();
        music.setName(req.getParameter("name"));
        music.setArname(req.getParameter("arname"));
        music.setAlname(req.getParameter("alname"));
        log.info("歌名："+music.getName());
        String imgpath = musicToolBiz.buildMusicPath("/musicimg/",file.getOriginalFilename(),music);
        log.info(imgpath);
        upLoadBiz.saveMultipartFile(file, DkPath.DataPath+imgpath);
        DkResponse<String> dkResponse = new DkResponse<>();
        dkResponse.setData(imgpath);
        return dkResponse;
    }

}
